package com.agritech.controller;

import com.agritech.common.Result;
import com.agritech.entity.Knowledge;
import com.agritech.service.KnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 知识控制器
 */
@RestController
@CrossOrigin
@RequestMapping("/api/knowledge")
public class KnowledgeController {

    @Autowired
    private KnowledgeService knowledgeService;

    /**
     * 根据分类ID获取知识列表
     */
    @GetMapping("/category/{categoryId}")
    public Result getKnowledgeByCategory(@PathVariable Long categoryId) {
        return Result.ok(knowledgeService.getKnowledgeByCategory(categoryId));
    }

    /**
     * 根据ID获取知识详情
     */
    @GetMapping("/{id}")
    public Result getKnowledgeById(@PathVariable Long id) {
        return Result.ok(knowledgeService.getKnowledgeById(id));
    }

    /**
     * 获取最新知识
     */
    @GetMapping("/latest/{limit}")
    public Result getLatestKnowledge(@PathVariable int limit) {
        return Result.ok(knowledgeService.getLatestKnowledge(limit));
    }

    /**
     * 添加新知识
     */
    @PostMapping
    public Result addKnowledge(@RequestBody Knowledge knowledge) {
        boolean success = knowledgeService.addKnowledge(knowledge);
        return success ? Result.ok("添加成功") : Result.error("添加失败");
    }

    /**
     * 更新知识信息
     */
    @PutMapping("/update/{id}")
    public Result updateKnowledge(@PathVariable int id, @RequestBody Knowledge knowledge) {
        knowledge.setId(id); // 确保 ID 被正确设置
        boolean success = knowledgeService.updateKnowledge(knowledge);
        return success ? Result.ok("更新成功") : Result.error("更新失败");
    }


    /**
     * 删除知识
     */
    @DeleteMapping("/{id}")
    public Result deleteKnowledge(@PathVariable Long id) {
        boolean success = knowledgeService.deleteKnowledge(id);
        return success ? Result.ok("删除成功") : Result.error("删除失败");
    }

    /**
     * 根据关键词查询知识列表
     * @param keywords 关键词
     * @return 统一响应结果
     */
    @RequestMapping("/list")
    public Result list(@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords) {
        List<Knowledge> knowledgeList = knowledgeService.list(keywords);
        return Result.ok(knowledgeList);
    }

    /**
     * 分页获取知识列表
     */
    @GetMapping
    public Result getKnowledgeList(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize
    ) {
        if (page < 1) page = 1;
        if (pageSize < 1) pageSize = 10;
        return Result.ok(knowledgeService.getKnowledgeList(page, pageSize));
    }



}